//
//  SEUserInfoViewController.swift
//  SmartEyeForDoctor
//
//  Created by qdsg on 2021/5/4.
//

import UIKit

enum SEUserInfoViewControllerType {
    case register
    case mine
}

class SEUserInfoViewController: SEBaseViewController {

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.isHidden = viewModel.type == .mine
            tableView.tableFooterView = tableFooterView
            tableView.rowHeight = 50
            tableView.separatorColor = UIColor.init(hex: "EBECF0")
            tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            tableView.keyboardDismissMode = .onDrag
            tableView.register(UINib(nibName: SEDoctorTitleTextFieldCell.className, bundle: nil), forCellReuseIdentifier: SEDoctorTitleTextFieldCell.reuseId)
            tableView.register(SEUserInfoStatusCell.nibForCell(), forCellReuseIdentifier: SEUserInfoStatusCell.reuseIdentifier())
            tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.reuseIdentifier())
        }
    }

    var viewModel = SEUserInfoViewModel(withLoading: true)

    convenience init(authViewModel: SEAuthViewModel) {
        self.init(type: .register)
        viewModel.authViewModel = authViewModel
    }

    convenience init(type: SEUserInfoViewControllerType) {
        self.init()
        viewModel.type = type
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "个人信息"
        if viewModel.type == .mine {
            requestUserInfo()
        }
        // Do any additional setup after loading the view.
    }

    override func setupUI() {
        super.setupUI()

        viewModel.updateData = { status in
            switch status {
            case .success:
                if self.viewModel.type == .mine {
                    self.tableView.isHidden = false
                    self.tableView.reloadData()
                } else {
                    AppDelegate.setupXylink()
                    self.pushToDoctorAuth()
                }
            case .auth(let msg):
                if self.viewModel.type == .mine{
                    self.presentLoginViewController(selector: #selector(self.requestUserInfo)) {
                        SEHUD.showError(message: msg)
                    }
                } else {
                    SEHUD.showError(message: msg)
                }
            case .failure(let msg):
                if self.viewModel.type == .mine {
                    SEHUD.showError(message: msg)
                } else {
                    SEHUD.showError(message: msg)
                    self.navigationController?.popToRootViewController(animated: true)
                }
            }
        }

        viewModel.loginHandler = { status in
            switch status {
            case .success:
                self.requestUserInfo()
            case .auth(let msg), .failure(let msg):
                SEHUD.showError(message: msg)
                self.navigationController?.popToRootViewController(animated: true)
            }
        }

        viewModel.editHandler = { status in
            switch status {
            case .success:
                SEHUD.show(message: "保存成功")
            case .auth(let msg):
                self.presentLoginViewController(selector: #selector(self.editUserInfo)) {
                    SEHUD.showError(message: msg)
            }
            case  .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }

    private lazy var tableFooterView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: 30 + 48 + 25))
        let btnView = SEConfirmBtnView(frame: CGRect(x: 15, y: 30, width: UIScreen.screenWidth - 30, height: 48))
        btnView.delegate = self
        btnView.title = viewModel.type == .register ? "下一步" : "保存"
        view.addSubview(btnView)
        return view
    }()

    private lazy var viewForHeaderInSectionOne: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: "#FFFBF1")
        let label = UILabel()
        label.numberOfLines = 0
        label.text = "请填写您所在执业医院的科室名称"
        label.textColor = UIColor(hex: "#F7B500")
        label.font = UIFont.regular(12)
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerY.equalTo(view.snp.centerY)
        }
        return view
    }()

    private lazy var viewForHeaderInSectionTwo: UIView = {
        let view = UIView()
        view.backgroundColor = Asset.background.color
        let label = UILabel()
        label.text = "以下注册时非必填"
        label.textColor = Asset.textLight.color
        label.font = UIFont.regular(15)
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerY.equalTo(view.snp.centerY)
        }
        return view
    }()

    private func tableFooterTextView(placeHolder: String, text: String, tag: Int) -> UIView {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: 105))
        view.backgroundColor = UIColor.white
        let textView = SETextView()
        textView.tag = tag
        textView.font = UIFont.systemFont(ofSize: 15)
        textView.frame = CGRect(x: 15, y: 0, width: UIScreen.screenWidth - 30, height: 90)
        textView.layer.cornerRadius = 4
        textView.layer.borderWidth = 1
        textView.layer.borderColor = UIColor.init(hex: "#E8E8E8").cgColor
        textView.layer.masksToBounds = true
        textView.placeholder = placeHolder
        textView.text = text
        textView.tvDelegate = self
        view.addSubview(textView)
        return view
    }
    
    private func presentAddressController() {
        view.endEditing(true)
        let addressVc = AddressViewController()
        addressVc.modalPresentationStyle = .custom
        addressVc.chooseClosure = { model in
            self.viewModel.model.province = model.provinceId
            self.viewModel.model.provinceName = model.provinceName
            self.viewModel.model.city = model.cityId
            self.viewModel.model.cityName = model.cityName
            self.viewModel.model.region = model.areaId
            self.viewModel.model.regionName = model.areaName
            self.tableView.reloadData()
        }
        present(addressVc, animated: true) {
            addressVc.view.backgroundColor = UIColor.black.withAlphaComponent(0.36)
        }
    }

    private func showDeptsPickerView() {
        view.endEditing(true)
        let picker = UINib.loadViewFrom(CommonPickerView.self)
        picker.frame = CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: UIScreen.screenHeight)
        picker.show(type: .departMent)
        picker.selectedClosure = { model in
            self.viewModel.model.standardId = model.code
            self.viewModel.model.standardName = model.name
            self.tableView.reloadData()
        }
    }

    private func showHospitalPickerView(){
        view.endEditing(true)
        guard !viewModel.model.province.isEmpty else {
            SEHUD.showError(message: "请先选择行政区域")
            return
        }
        let picker = UINib.loadViewFrom(CommonPickerView.self)
        picker.frame = CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: UIScreen.screenHeight)
        picker.viewModel.provinceId = viewModel.model.province
        picker.viewModel.cityId = viewModel.model.city
        picker.viewModel.regionId = viewModel.model.region
        picker.show(type: .hospital)
        picker.selectedClosure = { model in
            self.viewModel.model.hospitalId = model.code
            self.viewModel.model.hospitalName = model.name
            self.tableView.reloadData()
        }
    }

    private func showJobTitlePickerView(){
        view.endEditing(true)
        let picker = UINib.loadViewFrom(CommonPickerView.self)
        picker.frame = CGRect(x: 0, y: 0, width: UIScreen.screenWidth, height: UIScreen.screenHeight)
        picker.viewModel.provinceId = viewModel.model.province
        picker.viewModel.cityId = viewModel.model.city
        picker.viewModel.regionId = viewModel.model.region
        picker.show(type: .jobtitle)
        picker.selectedClosure = { model in
            self.viewModel.model.jobTitleCode = model.code
            self.viewModel.model.jobTitle = model.name
            self.tableView.reloadData()
        }
    }

    private func pushToDoctorAuth() {
        let type: SEDoctorAuthViewControllerType = viewModel.type == .register ? .register : .mine
        let vc = SEDoctorAuthViewController(type: type, userInfoModel: viewModel.model)
        if type == .mine {
            vc.submitSucessHandler = {
                self.requestUserInfo()
            }
        }
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: UITableViewDataSource, UITabBarDelegate

extension SEUserInfoViewController: UITableViewDataSource, UITableViewDelegate {

    // MARK: UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == viewModel.dataSource.count ? 1 : viewModel.dataSource[section].count
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.dataSource.count + 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == viewModel.dataSource.count {
            if viewModel.type == .mine {
                let cell = tableView.dequeueReusableCell(withIdentifier: SEUserInfoStatusCell.reuseIdentifier(), for: indexPath) as! SEUserInfoStatusCell
                cell.delegate = self
                cell.updateData(viewModel)
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.reuseIdentifier(), for: indexPath)
                return cell
            }
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: SEDoctorTitleTextFieldCell.reuseId, for: indexPath) as! SEDoctorTitleTextFieldCell
            cell.delegate = self
            cell.updateCell(model: viewModel.dataSource[indexPath.section][indexPath.row], indexPath: indexPath)
            return cell
        }
    }

    // MARK: UITabBarDelegate

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        switch section {
        case 1: return viewForHeaderInSectionOne
        case 2: return viewForHeaderInSectionTwo
        default:
            var placeHolder = ""
            var text = ""
            var tag = 0
            if section == 3 {
                tag = 100
                placeHolder = "请输入您的介绍"
                text = viewModel.model.introduction
            }
            if section == 4 {
                tag = 101
                placeHolder = "请输入您的擅长"
                text = viewModel.model.speciality
            }
            return tableFooterTextView(placeHolder: placeHolder, text: text, tag: tag)
        }
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        switch section {
        case 1, 2: return 50
        case 3, 4: return 105
        default: return 0
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == viewModel.dataSource.count {
            return viewModel.type == .mine ? 50 : 0.01
        } else {
            return 50
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.section < viewModel.dataSource.count else {
            return
        }
        let model = viewModel.dataSource[indexPath.section][indexPath.row]
        if !model.editEnable {
            view.endEditing(true)
            SEHUD.showError(message: "\(model.title)不支持修改")
        }
    }

}

extension SEUserInfoViewController: SEDoctorTitleTextFieldCellDelegate {
    func patientTitleTextFieldCellDidEndEdit(titleTextFieldCell: SEDoctorTitleTextFieldCell, indexPath: IndexPath) {
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                viewModel.model.name = titleTextFieldCell.textField.text!
            case 1:
                viewModel.model.idCard = titleTextFieldCell.textField.text!
            case 2:
                presentAddressController()
            case 3:
                showHospitalPickerView()
            default:
                print("\(indexPath.section),\(indexPath.row)")
            }
        case 1:
            switch indexPath.row {
            case 0:
                viewModel.model.deptName = titleTextFieldCell.textField.text!
            case 1:
                showDeptsPickerView()
            case 2:
                showJobTitlePickerView()
            default:
                print("\(indexPath.section),\(indexPath.row)")
            }
        default:
            print("\(indexPath.section),\(indexPath.row)")
        }
    }
}


// MARK: - SETextViewDelegate

extension SEUserInfoViewController: SETextViewDelegate {
    func textViewDidEndEditing(_ textView: UITextView) {
        if textView.tag == 100 {
            viewModel.model.introduction = textView.text
        }
        if textView.tag == 101 {
            viewModel.model.speciality = textView.text
        }
    }
}

// MARK: - SEConfirmBtnViewDelegate

extension SEUserInfoViewController: SEConfirmBtnViewDelegate {
    func confirmBtnViewAction(view: SEConfirmBtnView) {
        self.view.endEditing(true)
        if viewModel.type == .register {
            rquesetRegister()
        } else {
            editUserInfo()
        }
    }
}
// MARK: - SEUserInfoStatusCellDelegate

extension SEUserInfoViewController: SEUserInfoStatusCellDelegate {
    func userInfoStatusCellBtnAction() {
        pushToDoctorAuth()
    }
}

// MARK: - APIRequest

extension SEUserInfoViewController {

    func rquesetRegister() {
        viewModel.requestRegister()
    }

    @objc func requestUserInfo() {
        viewModel.requestUserInfo()
    }

    @objc func editUserInfo() {
        viewModel.editUserInfo()
    }
}

